/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.json.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import net.apexes.commons.lang.Dates;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

/**
 *
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class AdaptiveDateJsonDeserializer extends JsonDeserializer<Date> {

    public static final AdaptiveDateJsonDeserializer INSTANCE = new AdaptiveDateJsonDeserializer();

    protected AdaptiveDateJsonDeserializer() {
    }

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        String dateStr = jp.getText();
        String temp = dateStr; // 备份原始数据
        try {
            return Dates.parseAdaptive(dateStr);
        } catch (ParseException e) {
            throw new JsonDateParseException(temp, e);
        }
    }

    /**
     *
     * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
     *
     */
    public static class JsonDateParseException extends JsonProcessingException {

        private static final long serialVersionUID = 1L;

        protected JsonDateParseException(String msg, Throwable rootCause) {
            super(msg, rootCause);
        }

    }
}
